<template>
  <div class="boxContent">
    <div class="appBox">
      <div class="searchList">
        <el-form :model="state.params"
                 ref="FormInstance "
                 class="boxFrom">
          <div class="searchBox">
            <template v-for="(item, index) in state.totalInputColumns"
                      :key="index">
              <el-form-item v-if="item.type == 'input'">
                <el-input v-model="state.params[item.key]"
                          :placeholder="item.label"></el-input>
              </el-form-item>
              <el-form-item v-if="item.type == 'select'">
                <el-select v-model="state.params[item.key]"
                           :placeholder="item.label"
                           clearable
                           v-if="item.key == 'cid'">
                  <el-option />
                </el-select>
                <el-select v-model="state.params[item.key]"
                           :placeholder="item.label"
                           clearable
                           v-if="item.key == 'type'">
                  <el-option label="平台"
                             :value="0" />
                  <el-option label="企业"
                             :value="1" />
                </el-select>
                <el-select v-model="state.params[item.key]"
                           :placeholder="item.label"
                           clearable
                           v-if="item.key == 'status'">
                  <el-option label="正常"
                             :value="0" />
                  <el-option label="禁用"
                             :value="1" />
                </el-select>

                <el-cascader v-model="state.params[item.key]"
                             :options="state.propsCity"
                             :props="state.props"
                             :placeholder="item.label"
                             clearable
                             v-if="item.key == 'city'" />
              </el-form-item>
            </template>
          </div>

          <el-form-item class="btns">
            <el-button v-preventReClick
                       type="primary"
                       @click="methods.handleAction('add')"
                       v-permission="1101">创建角色</el-button>
            <el-button v-preventReClick
                       type="primary"
                       plain
                       @click="methods.handleAction('query')">搜索</el-button>
            <el-button v-preventReClick
                       @click="methods.handleAction('reset')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tabaleBox">
        <el-table border
                  v-loading='state.loading'
                  :data="state.tableData"
                  style="width: 100%"
                  :header-cell-style="{ color: '#000' }">

          <el-table-column prop="companyName"
                           label="企业名称"
                           show-overflow-tooltip
                           align="elft" />
          <el-table-column prop="createdAt"
                           label="创建时间"
                           show-overflow-tooltip
                           align="center"
                           width="120">
          </el-table-column>
          <el-table-column prop="createdName"
                           label="创建者"
                           show-overflow-tooltip
                           align="left"
                           width="110">
          </el-table-column>
          <el-table-column prop="name"
                           label="角色名称"
                           show-overflow-tooltip
                           align="left"
                           width="120">
          </el-table-column>
          <el-table-column prop="remark"
                           label="角色备注说明"
                           show-overflow-tooltip
                           align="left" />
          <el-table-column prop="status"
                           label="状态"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <div v-if="scope.row.status == 0"
                   class="primary">正常</div>
              <div v-if="scope.row.status == 1"
                   class="error">禁用</div>
            </template>
          </el-table-column>
          <el-table-column prop="type"
                           label="平台"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <div v-if="scope.row.type == 0"
                   class="">平台</div>
              <div v-if="scope.row.type == 1"
                   class="">企业</div>
            </template>
          </el-table-column>

          <el-table-column prop="updatedAt"
                           label="更新时间"
                           show-overflow-tooltip
                           align="center"
                           width="180">
          </el-table-column>
          <el-table-column prop="updatedName"
                           label="更新人"
                           show-overflow-tooltip
                           width="100">
          </el-table-column>

          <el-table-column prop="btns"
                           label="操作"
                           show-overflow-tooltip
                           align="center"
                           width="100"
                           fixed="right">
            <template #default="scope">
              <div class="flex_sb btnsDatil">
                <div @click="methods.handleAction('edit', scope.row)"
                     v-permission="1103">编辑</div>
                <div @click="methods.handleAction('role', scope.row)"
                     v-permission="1102">授权</div>
                <!-- <div @click="methods.handleAction('delete', scope.row)">
                  删除
                </div> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination background
                       v-model:current-page="state.params.pageNum"
                       v-model:page-size="state.params.pageSize"
                       :page-sizes="[10, 20, 30, 50]"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="state.totalSize"
                       @size-change="methods.handleSizeChange"
                       @current-change="methods.handleCurrentChange" />
      </div>

      <el-dialog v-model="state.elDialog"
                 center
                 v-if="state.elDialog"
                 :title="state.dialogData.data.name + ' - 授权'"
                 :width="$px2rem('650px')"
                 top="15vh">
        <!-- default-expand-all -- 全部展开 -->
        <!-- :default-expanded-keys="[2,3]" -- 部分展开 -->
        <!--  :default-checked-keys="[5,4]" -- 默认选中的数据 -->

        <el-scrollbar :height="$px2rem('300px')">
          <el-tree ref="treeRef"
                   :data="state.dialogData.list"
                   show-checkbox
                   node-key="id"
                   :check-strictly="true"
                   highlight-current
                   :getCheckedKeys="state.dasa"
                   @check="(data, index) => methods.changeTree(data, index)"
                   :props="state.dialogData.defaultProps"
                   :default-checked-keys="state.defaultCheckedNodes" />
        </el-scrollbar>
        <div class="mt20 tar">
          <el-button v-preventReClick
                     @click="methods.roleAddMenu"
                     type="primary">确定授权</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  reactive,
  toRefs,
  defineComponent,
  getCurrentInstance,
} from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const app = getCurrentInstance()?.proxy;
const initState = () => {
  return {
    defaultCheckedNodes: [],
    dialogData: {
      data: {},
      list: [],
      defaultProps: {
        children: "children",
        label: "menuName",
      },
    },
    loading: false,
    elDialog: false,
    totalSize: 0,
    tableData: [],
    params: {
      pageNum: 1,
      pageSize: 10,
      name: "",
      cid: '',
      type: '',
      status: '',
    },
    totalInputColumns: [
      { key: "name", label: "角色名称", type: "input" },
      { key: "status", label: "状态", type: "select" },
      { key: "type", label: "平台", type: "select" },
    ],
  };
};
const state = reactive(initState());
onMounted(() => {
  methods.getDataList();
});
const methods = {
  changeTree (data, index) {

    if (index.checkedKeys) {
      state.dialogData.checkedKeys = index.checkedKeys
    }
    if (index.checkedKeys.includes(data.id)) {
      console.log(data, index, '=');
      methods.selectChildren(data, true) // 选中子节点
    }// 选中

  },
  selectChildren (data, checked) {

    data && data.children && data.children.map(item => {
      app.$refs.treeRef.setChecked(item.id, checked);
      if (state.dialogData.checkedKeys.includes(item.id) == false) {
        state.dialogData.checkedKeys.push(item.id)
      }
      if (data.children) {
        methods.selectChildren(item, checked)
      }
    });
  },

  handleAction (type, data) {
    switch (type) {
      case "role": //授权
        state.dialogData.data = data;
        methods.getroleList();
        methods.getUserMenu()
        state.elDialog = true;
        break;
      case "query": //查询
        methods.getDataList();
        break;
      case "reset": // 重置
        state.params = initState().params;
        break;
      case "add": // 编辑
        router.push("/roleAdd");
        break;
      case "edit": // 编辑
        router.push("/roleAdd?id=" + data.id);
        break;
      case "state": // 状态开关
        methods.getDataList();
        break;
      case "delete": // 删除
        ElMessageBox.confirm("请确认是否删除该招聘职位?", "删除招聘职位", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            app.$http.get("/position/deleteById?id=" + data.id).then((res) => {
              methods.getDataList();
              ElMessage({
                type: "success",
                message: "已删除",
              });
            });
          })
          .catch(() => {
            methods.getDataList();
            ElMessage({
              type: "info",
              message: "已取消",
            });
          });

        break;
    }
  },
  //   授权数据
  getUserMenu () {
    app.$http
      .get("/sys/role/has/last/menu/byid?roleId=" + state.dialogData.data.id)
      .then((res) => {
        console.log(res);
        if (res.code == 200) {
          state.defaultCheckedNodes = res.data
        }
      });
  },

  //   授权菜单
  roleAddMenu () {
    app.$http
      .post("/sys/role/add/menu", {
        menuIds: state.dialogData.checkedKeys,
        roleId: state.dialogData.data.id,
      })
      .then((res) => {
        if (res.code == 200) {
          ElMessage({ type: "success", message: "授权成功" });
          state.elDialog = false;
        }
      });
  },
  //   菜单列表
  getroleList () {
    app.$http
      .get("/sys/role/has/menu/byroleid?roleId=" + state.dialogData.data.id)
      .then((res) => {
        console.log(res);
        if (res.data) {
          let list = []
          res.data.forEach(data => {
            if (data.hidden == 0) {
              list.push(data)
            }
          })
          state.dialogData.list = list;
        }
      });
  },
  getDataList () {
    state.loading = true
    app.$http
      .post("/sys/role/pageInfo", state.params)
      .then((res) => {
        state.tableData = res.data.list;
        state.totalSize = res.data.total;
        state.loading = false
      }).catch(() => {
        state.loading = false
      })
  },
  //分页变化
  handleSizeChange () {
    state.params.pageNum = 1;
    methods.getDataList();
  },
  //表格翻页
  handleCurrentChange () {
    methods.getDataList();
  },
};
</script>

<style lang="scss" scoped>
.appBox {
  background: #fff;
  border-radius: 5px;
  padding: 20px;
  height: calc(100% - 20px);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .tabaleBox {
    overflow: hidden;
    flex: 1;
  }
  .btnsDatil {
    color: #0079fe;
    cursor: pointer;
  }
  .pagination {
    margin-top: 20px;
    height: 50px;
    display: flex;
    justify-content: flex-end;
  }
  ::v-deep(.el-dialog__body) {
    max-height: 380px;
  }
  .imgs {
    flex-wrap: wrap;
    .forbox {
      // width: 150px;
      height: 150px;
      margin: 10px 0 0 10px;
    }
    .imgBox {
      height: 100%;
      width: auto;
    }
    .videoBox {
      width: auto;
      height: 100%;
    }
  }

  // .imgs .forbox:nth-child(4n + 1) {
  //   margin-left: 0;
  // }
}
</style>
